#include "IOUringEventLoop.h"
#include "Logger.h"
#include "Timestamp.h"

static thread_local IOUringEventLoop *t_loop_in_this_loop = nullptr;

IOUringEventLoop::IOUringEventLoop(int acceptFd)
    : hasPrepAccept_(false), acceptFd_(acceptFd), peerAddr_(),
      iouring_(2048, 1337, this), looping_(false), quit_(false),
      threadId_(CurrentThread::tid()), callingPendingFunctors_(false) {
    if (t_loop_in_this_loop != nullptr) {
        LOG_FATAL("Another EventLoop %p "
                  "exists in this thread %d",
                  t_loop_in_this_loop, threadId_);
    } else {
        t_loop_in_this_loop = this;
    }
}

void IOUringEventLoop::loop() {
    looping_ = true;
    quit_ = false;
    while (!quit_) {
        tryAddAccept(acceptFd_, 0);
        io_uring_submit(iouring_.ring());
        iouring_.handleCqes();
        doPendingFunctors();
    }
}

void IOUringEventLoop::doPendingFunctors() {
    std::vector<Functor> functors;
    callingPendingFunctors_ = true;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        // 把pendingFunctors_的内容转换到局部，解放pendingFunctors_，而且局部对象执行完成后会由栈销毁
        functors.swap(pendingFunctors_);
    }
    for (const Functor &functor : functors) {
        functor(); // 执行当前loop需要执行的回调操作
    }
    callingPendingFunctors_ = false;
}

void IOUringEventLoop::runInLoop(Functor cb) {
    if (isInLoopThread()) {
        cb();
    } else {
        // 在非当前loop线程中执行cb，就需要唤醒loop所在线程，然后执行cb
        queueInLoop(cb);
    }
}

void IOUringEventLoop::queueInLoop(Functor cb) {
    {
        std::unique_lock<std::mutex> lock(mutex_);
        pendingFunctors_.emplace_back(cb);
    }
    // 唤醒上面需要执行回调的线程
    if (!isInLoopThread() || callingPendingFunctors_) {
    }
}
